import json
import requests
import base64
import os
import Log
from io import BytesIO
from PIL import Image
from sys import version_info

class Controller():
    """图鉴验证码识别API类"""
    def __init__(self, uname='', pwd=''):
        self.uname = uname
        self.pwd = pwd
        if len(self.uname) == 0 or len(self.pwd) == 0:
            Log.Log().rwitelog("图鉴API平台用户名或密码为空", True)

    def runVerify(self, src):
    	if os.path.isfile(src) is False:
    		self.errMsg = '图片文件不存在："%s" 请检查验证码图片是否下载成功' % src
    		return False
    	else:
    		img = Image.open(src)
    		return self.base64_api(uname=self.uname, pwd=self.pwd, img=img)

    def base64_api(self, uname, pwd,  img):
	    img = img.convert('RGB')
	    buffered = BytesIO()
	    img.save(buffered, format="JPEG")
	    if version_info.major >= 3:
	        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
	    else:
	        b64 = str(base64.b64encode(buffered.getvalue()))
	    data = {"username": uname, "password": pwd, "image": b64}
	    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
	    if result['success']:
	        return result["data"]["result"]
	    else:
	    	self.errMsg	= result['message']
	    	return False
    	